from starlette.endpoints import HTTPEndpoint
from database import Session
import logging
from dao import DaoBureauMonRepSum, DaoPowerSupplyBureauOperator, DaoPowerSupplyBureauList
from dao import DaoAreaList
from starlette.responses import JSONResponse
from wxpublic import wx_public_message
import config
from sqlalchemy.exc import DBAPIError
import calendar,datetime

class BureauMonRepSumCheck(HTTPEndpoint):

    def __init__(self, scope):
        self._logger = logging.getLogger('MONTH_REP_CHECK')
        return super().__init__(scope)

    async def get(self, request):
        session = Session()
        try:
            bureauid = request.query_params["bureauid"]
            monthnum = request.query_params["monthnum"]
            return DaoBureauMonRepSum.get_monrep_check_info(session, bureauid, monthnum)
        finally:
            session.close()

    async def put(self, request):
        session = Session()
        try:
            dict_bwrs = await request.json()
            bureauid = dict_bwrs.get("bureauid")
            monthnum = dict_bwrs.get("monthnum")
            DaoBureauMonRepSum.update_mon_info_check(session, dict_bwrs)
            session.commit()
        except Exception:
            session.rollback()
            return JSONResponse({"result": "0"})
        else:
            self._logger.debug(f'Target Bureau: {bureauid}')
            from sqlalchemy.exc import SQLAlchemyError
            try:
                # 这里需要根据审核情况推送审核提醒
                # 审核结果推送
                if dict_bwrs['flag'] in ['2', '3']:
                    # 需要提醒，先获取需要提醒的人员OpenID，然后根据状态推送信息
                    from model.ModCompanyOperator import CompanyOperator
                    from model.ModDepartmentVsBureau import DepartmentVsBureau
                    from wxenterprise.wx_enterprise_message import send_to_user
                    target_employees = session.query(CompanyOperator)\
                        .join(DepartmentVsBureau, DepartmentVsBureau.departmentid == CompanyOperator.departmentid)\
                        .filter(DepartmentVsBureau.bureauid == bureauid)\
                        .filter(CompanyOperator.audit_permission == '1')\
                        .filter(CompanyOperator.company_employee == '0')\
                        .all()
                    msg = f'{monthnum[0:7]}月月报已被审核退回，请及时修改。'\
                        if dict_bwrs['flag'] == '3'\
                        else f'{monthnum[0:7]}月月报已审核通过。'
                    for person in target_employees:
                        send_to_user(person.openid, msg)
            except SQLAlchemyError:
                self._logger.warn(f'审核状态提醒发送失败，未找到目标人员。')
            finally:
                session.rollback()

            if dict_bwrs['flag'] == '2':
                list_operator = DaoPowerSupplyBureauOperator.get_operator_list(session, bureauid)
                bureau_info = DaoPowerSupplyBureauList.get_bureau_info_sent(session, bureauid)
                area_info = DaoAreaList.get_area_info(session, bureau_info.get("area_flag"))
                monego = f'第{monthnum[0:7]}期'
                year = monthnum[0:4]
                month = monthnum[5:7]

                # 获取当月第一天的星期和当月的总天数
                firstdayweekday, monthcou = calendar.monthrange(int(year), int(month))
                # 获取当月的第一天
                firstDay = datetime.date(year=int(year), month=int(month), day=1)
                lastDay = datetime.date(year=int(year), month=int(month), day=int(monthcou))
                monrange = f'{firstDay}至{lastDay}'
                for operator in list_operator:
                    wx_public_message.send_template_message(operator["openid"],
                                          config.TEMPLATE_PERIOD_REPORT,
                                          {
                                              "first": {
                                                  "value": f'您好，{monego}采集运维月报已生成，请查阅！',
                                                  "color": "#000000"
                                              },
                                              "keyword1": {
                                                  "value": f'{bureau_info.get("name")}供电公司',
                                                  "color": "#1736c0"
                                              },
                                              "keyword2": {
                                                  "value": "采集运维项目部",
                                                  "color": "#1736c0"
                                              },
                                              "keyword3": {
                                                  "value": monrange,
                                                  "color": "#1736c0"
                                              },
                                              "remark": {
                                                  "value": "您现在可以查阅报告信息了。",
                                                  "color": "#000000"
                                              }
                                          })
            return JSONResponse({"result": "1"})
        finally:
            session.close()


class BureauMonRepSumCheckList(HTTPEndpoint):

    async def get(self, request):
        session = Session()
        try:
            return DaoBureauMonRepSum.get_monrep_check_list(session)
        finally:
            session.close()


class BureauMonRepSumCheckCount(HTTPEndpoint):
    async def get(self, request):
        session = Session()
        try:
            bureauid = request.query_params["bureauid"]
            flagid = request.query_params["flagid"]
            cou = DaoBureauMonRepSum.get_moncheck_count(session, bureauid, flagid)
            return JSONResponse({"result": cou})
        finally:
            session.close()
